<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #addOperator="{ model, field }">
        <Tag color="green" v-if="model[field]" closable @close="handleDeleteOperator">
          {{ model['userName'] }}[{{ model[field] }}]
        </Tag>
        <Button @click="addOperator">+</Button>
      </template>
      <template #addOrg="{ model, field }">
        <Tag color="green" v-for="tag in model['deptNameList']" v-if="model[field]" closable @close="handleDeleteOrg">
          {{ tag }}
        </Tag>
        <Button @click="addOrg">+</Button>
      </template>
    </BasicForm>
    <!-- 选择管理员 -->
    <StaffSelector @register="registerOperatorModal" @success="handleSelectOperatorSuccess" />
    <!-- 选择部门 -->
    <OrgSelector @register="registerOrgModal" @success="handleSelectOrgSuccess" />
  </BasicModal>

</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { Button, Tag, } from 'ant-design-vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import StaffSelector from '/@/views/components/selector/staffSelector/index.vue';
import OrgSelector from '/@/views/components/selector/orgSelector/index.vue';
import { useModal } from '/@/components/Modal';

import { formSchema } from './user.data';
import { update, add } from '/@/api/privilege/sysdatarange';


export default defineComponent({
  name: 'UserModal',
  components: { BasicModal, BasicForm, StaffSelector, OrgSelector, Button, Tag, },
  emits: ['success', 'register'],
  setup(_, { emit }) {

    const isUpdate = ref(true);
    //选中的管理员
    const selectedOperatorList = ref([]);
    //选中的类型
    const selectedAdminType = ref(0);
    //选中的部门
    const selectedOrgList = ref([]);

    const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
      labelWidth: 100,
      schemas: formSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 23,
      },
    });


    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      setFieldsValue({
        ...data.record,
      });
    });

    const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '修改'));

    async function handleSubmit() {
      try {
        setModalProps({ confirmLoading: true });
        const values = await validate();
        console.log('handleSubmit 提交表单：', values)
        if (values.id) {
          await update(values);
        } else {
          await add(values);
        }
        closeModal();
        emit('success');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    //选人弹框
    const [registerOperatorModal, { openModal: openPersonalSelector, setModalProps: setPersonalModalProps }] = useModal();
    // 弹出选择管理员
    function addOperator() {
      const values = validate();
      if (values.id) {
        return;
      }

      openPersonalSelector(true, {
        selectorProps: {
          multiSelect: false,
          selectedList: selectedOperatorList.value,
        }
      });
      setPersonalModalProps({
        title: `选择管理员`,
        bodyStyle: { padding: '0px', margin: '0px' },
        width: 850, height: 450,
        showOkBtn: true, showCancelBtn: false
      });
    }
    // 选择管理员成功回调
    async function handleSelectOperatorSuccess(selectedList: any) {
      if (selectedList && selectedList.length > 0) {
        emit('success', selectedList);
        setFieldsValue({
          userId: selectedList[0].id,
          userName: selectedList[0].name
        });
      }
    }
    // 删除选择审批人成功回调
    async function handleDeleteOperator() {
      selectedOperatorList.value = [];
    }

    //选部门弹框
    const [registerOrgModal, { openModal: openOrgSelector, setModalProps: setOrgModalProps }] = useModal();
    // 弹出选择部门
    function addOrg() {
      openOrgSelector(true, {
        selectorProps: {
          multiSelect: true,
          selectedList: selectedOrgList.value,
        }
      });
      setOrgModalProps({
        title: `选择部门`,
        bodyStyle: { padding: '0px', margin: '0px' },
        width: 850, height: 450,
        showOkBtn: true, showCancelBtn: false
      });
    }
    // 选择部门成功回调
    async function handleSelectOrgSuccess(selectedList: any) {
      if (selectedList && selectedList.length > 0) {
        emit('success', selectedList);
        var deptNameList = []
        var idList = []
        selectedList.forEach((item) => {
          idList.push(item.id);
          deptNameList.push(item.name);
        });

        setFieldsValue({
          deptId: idList.join(','),
          deptName: deptNameList.join(','),
          deptNameList: deptNameList,
        });
        console.log('handleSelectOrgSuccess 成功回调：', idList.join(','), deptNameList)
      }
    }
    // 删除选择审批人成功回调
    async function handleDeleteOrg() {
      selectedOrgList.value = [];
    }

    return {
      addOperator, registerOperatorModal, handleSelectOperatorSuccess, handleDeleteOperator,
      addOrg, registerOrgModal, handleSelectOrgSuccess, handleDeleteOrg,
      registerModal, registerForm, getTitle, handleSubmit
    };
  },
});
</script>
